package sample.tangocho.dataaccess;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sample.tangocho.model.Tangocho;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TangochoDaoImpl extends SQLiteDao implements TangochoDao {

	public TangochoDaoImpl(Context context) {
		super(context);
	}

	@Override
	public long insertTangocho(String title) {

		ContentValues values = new ContentValues();
		values.put("title", title);
		values.put("last_updated", new Date().getTime());
		return getTangochoSQLiteOpenHelper().getWritableDatabase().insert("tangocho",
				null, values);

	}

	@Override
	public List<Tangocho> selectTangochoList() {
		SQLiteDatabase db = getTangochoSQLiteOpenHelper().getWritableDatabase();

		List<Tangocho> tangochoList = new ArrayList<Tangocho>();

		Cursor cursor = db
				.query("tangocho", null, null, null, null, null, null);

		if (cursor.moveToFirst()) {
			do {
				String title = cursor.getString(cursor.getColumnIndex("title"));
				int id = cursor.getInt(cursor.getColumnIndex("_id"));
				long lastUpdated = cursor.getLong(cursor
						.getColumnIndex("last_updated"));

				Tangocho tangocho = new Tangocho();
				tangocho.setTitle(title);
				tangocho.setId(id);
				tangocho.setLastUpdated(lastUpdated);

				tangochoList.add(tangocho);
			} while (cursor.moveToNext());
		}

		return tangochoList;
	}

	@Override
	public void deleteTangocho(int id) {
		SQLiteDatabase db = getTangochoSQLiteOpenHelper().getWritableDatabase();
		db.delete("tangocho", "_id = ?", new String[] { String.valueOf(id) });
	}

	@Override
	public void updateTangocho(Tangocho tangocho) {
		SQLiteDatabase db = getTangochoSQLiteOpenHelper().getWritableDatabase();
		ContentValues contentValues = new ContentValues();
		contentValues.put("title", tangocho.getTitle());
		contentValues.put("last_updated", new Date().getTime());
		db.update("tangocho", contentValues, "_id = ?",
				new String[] { String.valueOf(tangocho.getId()) });

	}

}
